<template>
  <a-layout has-sider class="BasicLayout" >

    <!-- a-layout-sider 组件可以控制其内部菜单的展开折叠 -->
    <a-layout-sider v-model:collapsed="collapsed" class="left-layout" v-show="isNeedMenu" :width="menuWidth">
      <h1 class="logo">
        <img :src="logo" alt="sysLogo">
      </h1>
  
      <AsideMenu ref="menuRef" />
    </a-layout-sider>

    <a-layout class="right-layout"
      :style="{ marginLeft: isNeedMenu ? rightLayoutLeftMargin + 'px' : 0, transition: isRightTransition ? `margin-left ${transitionTime}` : 'none' ,backgroundColor:isNeedLayout?'':'white'}">
     
      <a-layout-header class="layout-header" v-show="isNeedLayout">
       
        <div class="header-left">
          <div class="collapsed-icon" style="cursor: pointer;"  @click="collapsed = !collapsed"  v-show="isNeedMenu">
            <!-- <a-tooltip placement="top" :title="collapsed ? '点击展开菜单' : '点击折叠菜单'"> -->
                <MenuUnfoldOutlined  v-show="collapsed" style="color: white;" />
                <MenuFoldOutlined v-show="!collapsed" style="color: white;" />
            <!-- </a-tooltip> -->
          </div>

            <a-breadcrumb class="breadcrumb" :style="{marginLeft:'20px'}">
            <a-breadcrumb-item v-for="item, index in breadcrumbList" :key="index" >
              <!-- (!item.path) || (breadcrumbList.length - 1 == index) -->
              <span v-if="1">{{ item.breadcrumbName }}</span>
              <router-link v-else :to="{ name: item.name }">
                {{ item.breadcrumbName }}</router-link>
            </a-breadcrumb-item>
            </a-breadcrumb>
      </div>
       
      <div class="header-right">
        <div class="selectLang-container" style="margin-right: 22px;">
          <selectLang />
        </div>
        <a-dropdown  >
          <a-avatar shape="square" :size="36" :src="user.info.avatar?user.info.avatar:wsl3" />
          <template #overlay>
					<a-menu>
            <a-menu-item @click="logout">退出登录</a-menu-item>
            <a-menu-item @click="()=>{$window.open('https://blog.csdn.net/qq_61233877/article/details/131008600?spm=1001.2014.3001.5502')}">项目描述</a-menu-item>
					</a-menu>
				</template>
        </a-dropdown>
      </div>
      </a-layout-header>

    
      <div v-show="isNeedLayout && parseInt(tagNavHeight)"  class="fast-navTag-container">
        <NavTagBar   />
      </div>
     
      
    <a-layout-content class="content-layout" :style="{padding:isNeedLayout?'':0,width:isNeedLayout?'':'auto'}">
        <div class="pageView">  
        <Suspense>
			      <template #default>
							<router-view v-slot="{ Component }">
						 <!-- <transition mode="out-in" name="page" appear> -->
								<KeepAlive :exclude="[...noCachePages]">
									 <component :is="Component" />
								</KeepAlive>
						<!-- </transition> -->
				 </router-view>
						</template>
						<template #fallback> 
              <div class="loadingPage" ><a-spin tip="数据加载中..." v-if="0"></a-spin></div>
						</template>
				 </Suspense>
 
        </div>
      </a-layout-content>

      <a-layout-footer :style="{ textAlign: 'center',padding:'10px 0'}" class="layout-footer" v-show="isNeedLayout&&parseInt(footerHeght)">
        copyright &copy; <a target="_blank" href="https://gitee.com/gitee_lw/projects?sort=&scope=&state=public">lw</a>
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>
<script lang="ts" setup>
import { MenuFoldOutlined, MenuUnfoldOutlined ,SmileOutlined} from "@ant-design/icons-vue"
import logo from  "@/assets/logo.png"
import AsideMenu from "@/layouts/components/leftMenu/menu.vue"
import NavTagBar from "./components/navTag"
import selectLang from "./components/selectLang.vue"
import { ref, watch, computed, onBeforeUnmount, onMounted, Suspense,h } from "vue"
import { Modal,notification} from "ant-design-vue"
import { user as useUser, navTags as useNavTag } from "@/store"
import { useRoute } from "vue-router"
import type { RouteLocationNormalizedLoaded } from "vue-router";
import {homeRouteName} from "@/router/config"
import {primaryColor_hex, primaryColor_rgb,primaryColorFade} from "@/theme/config"
import wsl3 from "@/assets/imgs/wsl3.webp"

const menuWidth = 200
const menuWidth_collapsed = 80
const menuCollapsedScreenWidthPoint = 900
const headerHeigth = '64px'
const tagNavHeight = '39px'
// const footerHeght = '42px'
const footerHeght = '0px'
const transitionTime = '0.2s'
const collapsed = ref<boolean>(false)
const rightLayoutLeftMargin = ref(menuWidth)
const isRightTransition = ref(true)
const menuTheme='#ffffff'
const barBgColor=primaryColorFade(0.7)
const noCachePages=ref(new Set<string>([]))

type breadcrumbItemType = { breadcrumbName: string, path: string, children?: breadcrumbItemType[], name: string, activeName?: string, [key: string]: any }
const breadcrumbList = ref<breadcrumbItemType[]>([])

const route = useRoute()
const user = useUser()
const navTags = useNavTag()
// const t=ref(true)

const menuRef = ref<InstanceType<typeof AsideMenu>>()


const isNeedLayout = computed(() => {
  return !route.meta.hiddenLayout
})


const isNeedMenu = computed(() => {
  return !route.meta.hiddenMenu && isNeedLayout.value
  // return true
})

watch(isNeedMenu, (newV, _oldV) => {
  //console.log("isRightTransition",newV)
  // 解决从无菜单到有菜单时出现过渡的问题。因为此时菜单不具有过渡，因此右侧也不能过渡，300ms足够菜单渲染出来，因为渲染菜单的数据都是现有的，后续如果有问题加到500ms即可,如果还有问题只能剔除布局和菜单隐藏功能
  if (newV) setTimeout(() => { isRightTransition.value = true }, 300)
  else isRightTransition.value = false
}, { immediate: true })

const handleMenuActive = (route: RouteLocationNormalizedLoaded) => {
  menuRef.value?.changeActive()
  menuRef.value?.changeActivePath()
}

const handleNavTag = (route: RouteLocationNormalizedLoaded) => {
  if (!route.meta.noKeepAlive) {
    const tags = navTags.tags
    const index = tags.findIndex((v) => v.name === route.name)
    // console.log(index)
    if (index !== -1) {
      navTags.activeTag({ index, fullPath: route.fullPath })
    } else {
      const {title,affix}=route.meta
      const {fullPath,name}=route
      navTags.addTag({name,title,fullPath,affix:affix?true:false} as any)
    }
  } else navTags.clearActive()
}

const handleBreadcrumb = (route: RouteLocationNormalizedLoaded) => {
  // console.log({...route})
  // console.log(route.matched)
  const _breadcrumbList: breadcrumbItemType[] = []
  route.matched.forEach(v => {
    //if (v.path == "/") _breadcrumbList.push({ breadcrumbName: '首页', path: "/"+homeRouteName, name: homeRouteName })
    if (v.path != "/" && v.name != homeRouteName) _breadcrumbList.push({ breadcrumbName: (v.meta.title ?? v.name) as string, path: v.path, name: v.name as string })
  })
  if (_breadcrumbList[_breadcrumbList.length - 1])
    _breadcrumbList[_breadcrumbList.length - 1].path = ''
  // console.log(_breadcrumbList)
  breadcrumbList.value = _breadcrumbList
}

// 非缓存页设置。需要注意的是：要使得非缓存生效，非缓存页组件需要写name属性，且name属性的值要与路由配置的name属性值一致
const setNoCachePage=(newRoute: RouteLocationNormalizedLoaded)=>{
	if(newRoute.meta.noKeepAlive)
	noCachePages.value.add(newRoute.name as string)
  // console.log(noCachePages.value)
}

watch(
  route,
  (route, _oldRoute) => {
    // console.log({...route})   // 这样打印方便查看，toRaw也不管用
    // console.log(route,_oldRoute)
    handleMenuActive(route)
    handleNavTag(route)
    handleBreadcrumb(route)
    setNoCachePage(route)
  },
  { immediate: true }
)

watch(collapsed, (n, _o) => {
  // console.log(n)
  if (n) rightLayoutLeftMargin.value = menuWidth_collapsed
  else {
    rightLayoutLeftMargin.value = menuWidth
    menuRef.value?.changeOpen()
  }
})

const logout = () => {
  Modal.confirm({
    title: "确定要退出登录吗?",
    content: "",
    okText: "确定",
    cancelText: "取消",
    onOk: () => user.logout(route.fullPath),
    onCancel: () => { },
  })
}

const windowResize = () => {
  // console.log('widow resize')
  // console.log(document.documentElement.clientWidth)
  if (isNeedMenu) {
    //console.log("meun is readying change width")
    if (document.documentElement.clientWidth <= menuCollapsedScreenWidthPoint) {
      collapsed.value = true
    } else {
      collapsed.value = false
      menuRef.value?.changeOpen()
    }
  }
}

window.addEventListener("resize", windowResize)

onBeforeUnmount(() => {
  window.removeEventListener("resize", windowResize)
})

onMounted(() => {
  // console.log(document.documentElement.clientWidth)
  if (isNeedMenu && document.documentElement.clientWidth <= menuCollapsedScreenWidthPoint) {
    collapsed.value = true
  }

  notification.open({
        message: '欢迎',
        description:`欢迎${user.info.userName}来到本系统`,
        icon: () => h(SmileOutlined, { style: {color:primaryColor_hex} }),
  })
})
</script>
<style lang="less" scoped>
.logo {
  height: 32px;
  margin:16px 16px 25px;
  text-align: center;

  img{
				height: 42px;
				width: 42px;
	}
}

.left-layout {
  // overflow: auto;
  overflow-y: auto;
  overflow-x: hidden;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 10;
  background-color:v-bind(menuTheme);
  transition: all v-bind(transitionTime);
  // transition: all 0.8s;
  /*a- layout-sider 组件原有样式，保留all以免出错*/
}

.right-layout {

  .layout-header {
    background-color: v-bind(barBgColor);
    position: sticky;
    top: 0;
    right: 0;
    left: 0;
    display: flex;
    justify-content: space-between;
    padding: 0 12px 0;
    z-index: 9;
     
    .header-left{
        display: flex;
        align-items: center;

        :deep(.ant-breadcrumb span),:deep(.ant-breadcrumb span  a){
            color: white;
        }
        :deep(.ant-breadcrumb span  a:hover){
          color: rgb(216, 212, 212);
        }
    }


    .header-right {
      margin-right: 6px;
      user-select: none;
      width: 280px;
      align-self: flex-end;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }

  }

  .fast-navTag-container{
    padding: 8px 12px 1px;
    background-color: white;
    position: sticky;
    top: v-bind(headerHeigth);
    left: 0;
    right: 0;
    z-index: 999;
  }


  .content-layout {
     padding: 12px;

    .pageView{
      position: relative;
      overflow: auto;
      min-height: calc(100vh - v-bind(headerHeigth) - v-bind(tagNavHeight) - v-bind(footerHeght) - 24px);
      padding:12px;
      // padding: 20px 12px 0;
      background-color: white;
      
    }

    .loadingPage {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      z-index: 999;
    }
  }

  .layout-footer{
    background-color: v-bind(barBgColor);
  }

}



</style>
